import {createContext, useRef, useState} from 'react';
import {load} from "@2gis/mapgl";
import {Directions} from "@2gis/mapgl-directions";
import { apiKey} from "../api";

const RouteContext = createContext();

const RouteProvider = ({ children }) => {
    const mapRef = useRef(null);
    const directionsRef = useRef(null);
    const mapglAPIRef = useRef(null);
    const points = useRef([]);
    const markers = useRef([]);

    const initMap = (map_type, route = []) => {
        load().then((mapglAPILoaded) => {
            mapRef.current = new mapglAPILoaded.Map('map-container', {
                center: [44.51820573095013, 48.71073729295477],
                zoom: 15,
                key: apiKey,
            });

            const directions = new Directions(mapRef.current, {
                directionsApiKey: apiKey,
            });

            if (map_type === 'edit') {
                mapRef.current.on('click', mapClick);
            }

            mapglAPIRef.current = mapglAPILoaded;
            directionsRef.current = directions;

            if (route.length > 0) {
                points.current = route;

                // Добавляем маркеры для всех точек маршрута
                route.forEach(point => addMarker(point));

                // Подгоняем видимую область карты под маршрут
                if (route.length === 1) {
                    // Если точка одна, центрируем карту на ней с фиксированным зумом
                    mapRef.current.setCenter(route[0]);
                    mapRef.current.setZoom(14);
                } else {
                    const bounds = route.reduce((bounds, point) => bounds.extend(point), new mapglAPILoaded.LngLatBounds());
                    mapRef.current.fitBounds(bounds, {
                        padding: 100,
                        maxZoom: 16
                    });
                }

                // Рисуем маршрут только если это не режим 'markersOnly'
                if (map_type !== 'markersOnly') {
                    drawRoute();
                }
            } else {
                // Если маршрут пустой, добавляем маркер в центр карты
                const marker = new mapglAPILoaded.Marker(mapRef.current, {
                    coordinates: [44.51820573095013, 48.71073729295477],
                });
            }
        });
    }

    const addPoint = (newPoint) => {
        points.current = [...points.current, newPoint];
    };

    const addMarker = (coords) => {
        const newMarker = new mapglAPIRef.current.Marker(mapRef.current, {
            coordinates: coords,
            icon: 'https://docs.2gis.com/img/dotMarker.svg',
        });
        markers.current = [...markers.current, newMarker];
    };

    const drawRoute = () => {
        if (points.current.length > 1) {
            directionsRef.current.pedestrianRoute({ points: points.current });
        }
    }

    const clearMarkers = () => {
        markers.current.forEach((m) => {
            m.destroy();
        });
        markers.current = [];
    }

    const addPointFromAddress = (coords) => {
        console.log('addPointFromAddress')
        addMarker(coords);
        addPoint(coords);
        drawRoute();
    };

    const removeLastPoint = () => {
        console.log('removeLastPoint')
        points.current.pop();
        if (markers.current.length > 0) {
            markers.current.pop().destroy();
        }
        drawRoute();
    };

    const clearPoints = () => {
        console.log(' clearPoints');
        clearMarkers();
        points.current = [];
        directionsRef.current.clear();
    };

    const mapClick = (e) => {
        console.log(' click');
        const coords = e.lngLat;
        addMarker(coords);
        addPoint(coords);
        drawRoute();
    };

    return (
        <RouteContext.Provider value={{ mapRef, addPoint, removeLastPoint, clearPoints, initMap, mapClick, addPointFromAddress, points}}>
            {children}
        </RouteContext.Provider>
    );
};

export { RouteProvider, RouteContext };